// components/radioPicker/radioPicker.js
// import exThis from '../../mixins/extend/ex-this'
// const mixin = wx.initMixin(exThis)

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      value: ""
    },
    max: {
      type: Number,
      value: 99
    },
    selectedIds: {
      value: [],
      observer: function(value){
        const selectedItems = []
        const range = this.data.range
        // 找出相同ID项
        range.forEach(item=>{
          if(!item.id) return
          if(value.indexOf(item.id) != -1){
            selectedItems.push(item)
          }
        })
        this.setData({
          compSelectedIds: value,
          compSelectedItems: selectedItems
        })
      }
    },
    selectedItems: {
      value: [],
      observer: function(value){
        // 转换为id数组
        this.setData({
          compSelectedIds: value.map(item=>item.id),
          compSelectedItems: value
        })
      }
    },
    range: {
      value: [],
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: true,
    compSelectedIds: [],
    compSelectedItems: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    clickCancel() {
      this.triggerEvent("cancel")
    },
    clickSumbit() {
      let {
        compSelectedIds,
        compSelectedItems
      } = this.data
      this.triggerEvent("sumbit", {
        selectedIds: compSelectedIds,
        selectedItems: compSelectedItems
      })
    },
    clickItem(e) {
      let {
        item,
      } = e.currentTarget.dataset
      const compSelectedIds = this.data.compSelectedIds || []
      const compSelectedItems = this.data.compSelectedItems || []

      // 判断是否已添加 
      if (compSelectedIds.indexOf(item.id) == -1) {
        // 新增
        // 判断是否超过限制
        if(compSelectedIds.length >= this.data.max) {
          wx.showToast({
            icon: 'none',
            title: '最多只能选择' + this.data.max + '个',
          })
          return
        }
        compSelectedIds.push(item.id)
        compSelectedItems.push(item)
      } else {
        // 去掉
        const findDeleteIndex = compSelectedIds.findIndex(selectedId => selectedId == item.id)
        if (findDeleteIndex != -1) {
          compSelectedIds.splice(findDeleteIndex, 1)
          compSelectedItems.splice(findDeleteIndex, 1)
        }
      }
      this.setData({
        compSelectedIds,
        compSelectedItems
      })
    }
  }
})